/**
 * 
 */
package bai5.com.util;

/**
 * @author nglehien
 * Oct 21, 2012 - 9:04:26 PM
 */

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public final class FileUtil {

	private FileUtil() {

	}

	public static ArrayList<String> readFile(File file) throws IOException {
		FileInputStream fileInputStream = new FileInputStream(file);
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(fileInputStream, "UTF-8"));
		String data = null;
		ArrayList<String> arrayListData = new ArrayList<>();
		while ((data = bufferedReader.readLine()) != null) {
			arrayListData.add(data);
		}
		bufferedReader.close();
		return arrayListData;
	}

	public static ArrayList<String> reverse(ArrayList<String> arrayList) {
		ArrayList<String> temp = new ArrayList<>();
		for (int i = 0; i < arrayList.size(); i++) {
			String output = new String();
			String line = arrayList.get(i);
			String[] words = line.split(" ");
			for (int j = 0; j < words.length; j++) {
				StringBuilder stringBuilder = new StringBuilder(words[j]);
				stringBuilder = stringBuilder.reverse();
				stringBuilder.append(" ");
				output += stringBuilder.toString();
			}
			temp.add(output);
		}
		return temp;
	}

	public static File writeFile(ArrayList<String> datas) throws IOException {
		File file = File.createTempFile("temp", "tmp");
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		BufferedWriter bufferedWriter = new BufferedWriter(
				new OutputStreamWriter(fileOutputStream, "UTF-8"));
		for (int i = 0; i < datas.size(); i++) {
			String data = datas.get(i);
			bufferedWriter.write(data);
			bufferedWriter.newLine();
		}
		bufferedWriter.close();
		return file;
	}

	public static boolean createNewFile(ArrayList<String> datas, String dst)
			throws IOException {
		try {
			File file = new File(dst);
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			BufferedWriter bufferedWriter = new BufferedWriter(
					new OutputStreamWriter(fileOutputStream, "UTF-8"));
			for (int i = 0; i < datas.size(); i++) {
				String data = datas.get(i);
				bufferedWriter.write(data);
				bufferedWriter.newLine();
			}
			bufferedWriter.close();
			return true;
		} catch (IOException e) {
			return false;
		}
	}
}
